package cn.com.dhc.danlu.util;

import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * author: 李一方(<a href="mailto:liyifang@danlu.com">liyifang@danlu.com</a>)<br/>
 * version: 1.0.0<br/>
 * since: 2017-03-27 15:21
 *
 * <p>
 * String 工具
 * </p>
 */
public class StringUtil {
    /**
     * 根据"[]"渲染 String
     *
     * @param string
     *         string
     * @param hightLightColor
     *         高亮颜色
     * @param hightLightSize
     *         高亮字号
     *
     * @return 渲染后的字符串
     */
    public static SpannableString hightLight(String string, int hightLightColor, int hightLightSize) {
        String res = string.replace("[", "").replace("]", "");
        SpannableString s = new SpannableString(string);
        SpannableString s2 = new SpannableString(res);

        String rex = "\\[([^\\[\\]]*)\\]";

        Pattern p = Pattern.compile(rex);
        Matcher m = p.matcher(s);

        int i = 0;
        while (m.find()) {
            int start = m.start();
            int end = m.end();
            int dx = end - start - 2;
            if (i != 0) {
                start = start - i * 2;
            }
            s2.setSpan(new ForegroundColorSpan(hightLightColor), start, start + dx, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            s2.setSpan(new AbsoluteSizeSpan(hightLightSize), start, start + dx, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            i++;
        }
        return s2;
    }
}
